package com.ruiben.mall.impl;

import com.ruiben.mall.ICollectionService;
import com.ruiben.mall.mapper.ShopProductMapper;
import com.ruiben.mall.mapper.UserCollectionMapper;
import com.ruiben.mall.pojo.ShopProduct;
import com.ruiben.mall.pojo.UserCollection;
import org.n3r.idworker.Sid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
public class CollectionServiceImpl implements ICollectionService {


    @Autowired
    private Sid sid;

    @Autowired
    private UserCollectionMapper collectionMapper;

    @Autowired
    private ShopProductMapper productMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public boolean collGoods(UserCollection collection) {
        collection.setId(sid.nextShort());
        collection.setCollectiontime(new Date());
        int insert = collectionMapper.insert(collection);

        ShopProduct shopProduct = productMapper.selectByPrimaryKey(collection.getProductId());
        if (shopProduct == null){
            return false;
        }

        shopProduct.setCollNum(shopProduct.getCollNum() + 1);
        productMapper.updateByPrimaryKeySelective(shopProduct);

        return insert > 0;
    }

    @Override
    public UserCollection getCollectionByGoodsId(String goodsId) {
        Example example = new Example(UserCollection.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("productId",goodsId);
        return collectionMapper.selectOneByExample(example);
    }
}
